import axios from "axios";
import { ElMessage, ElLoading } from "element-plus";
import { isLogged, getLoggedUser, clearLogged } from "../utils/stateUtils";

const baseURL = "http://api.friendship.x-cloud.ml";

const request = axios.create({
  timeout: 60000,
  baseURL,
});
var loading;
request.interceptors.request.use((config) => {
  if (config.url !== "/user/heartBeat")
    loading = ElLoading.service({
      lock: true,
      text: "加载中",
      background: "rgba(0, 0, 0, 0.7)",
    });
  if (isLogged()) config.headers.set("token", getLoggedUser().token);
  return config;
});

request.interceptors.response.use(
  (response) => {
    if (response.config.url !== "/user/heartBeat") {
      // 2xx 范围内的状态码都会触发该函数。
      loading.close();
      const { data } = response;
      console.log("请求结果", data);
      if (data.success) return data;
      // 提示错误信息
      ElMessage.error(data.message);
      return Promise.reject(data.message);
    } else {
      return response;
    }
  },
  (error) => {
    if (error.config.url !== "/user/heartBeat") {
      loading.close();
      // 超出 2xx 范围的状态码都会触发该函数。
      if (!error.response) {
        ElMessage.error("服务器错误, 请联系开发者");
      }
      if (!error.response) {
        console.log(error);
      } else if (error.response.status === 403) {
        ElMessage.error("登录失效, 请重新登录");
        clearLogged();
      } else {
        ElMessage.error("服务器错误, 请查看控制台");
        console.log(error);
      }
    }
    return Promise.reject(error);
  }
);

export { request, baseURL };
